//
//  WBRefreshControl.swift
//  01sinablog
//
//  Created by ZhangZiang on 15/12/22.
//  Copyright © 2015年 ZhangZiang. All rights reserved.
//

import UIKit

private let refreshHeight : CGFloat = 60

enum WBRefreshStates : Int {
    case Normal = 0
    case Pulling = 1
    case Refreshing = 2
}

class WBRefreshControl: UIControl {

    override init(frame: CGRect) {
        
        let rect = CGRect(x: 0, y: -refreshHeight, width: ScreenW, height: refreshHeight)
        
        super.init(frame: rect)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI()
    {
        backgroundColor = UIColor(white: 0.9, alpha: 1)
        
        addSubview(textLabel)
        addSubview(iconView)
        addSubview(indicator)
        
        textLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self.snp_centerX).offset(15)
            make.centerY.equalTo(self.snp_centerY)
        }
        
        iconView.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(self.snp_centerY)
            make.centerX.equalTo(textLabel.snp_left).offset(-8)
        }
        
        indicator.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(iconView.snp_center)
        }
    }
    
    //记录上一次的状态
    private var oldState : WBRefreshStates = .Normal
    
    var refreshState : WBRefreshStates = .Normal {
        didSet {
            switch refreshState
            {
            case .Normal :
                iconView.hidden = false
                indicator.hidden = true
                indicator.stopAnimating()
                textLabel.text = "下拉刷新"
                iconView.transform = CGAffineTransformIdentity
                //修改contentInsert让刷新view回去
                if oldState == .Refreshing {
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        var insert = self.scrollView?.contentInset
                        insert?.top -= refreshHeight
                        self.scrollView?.contentInset = insert!
                    })
                }
              
            case .Pulling :
                textLabel.text = "放开刷新"
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.iconView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
                
            case .Refreshing :
                textLabel.text = "正在刷新"
                indicator.hidden = false
                indicator.startAnimating()
                iconView.hidden = true
                //修改contentInsert,可以产生让刷新view暂时停住不回去的效果
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    var insert = self.scrollView?.contentInset
                    insert?.top += refreshHeight
                    self.scrollView?.contentInset = insert!
                })
                
                //主动触发事件,让Home去loadData
                sendActionsForControlEvents(.ValueChanged)
            }
            
            oldState = refreshState
        }
    }
    
    //通过这个方法拿到父类,然后用kvo方法监听scrollview的contentoffset值
    override func willMoveToSuperview(newSuperview: UIView?) {
        
        if let superView = newSuperview as? UIScrollView
        {
            scrollView = superView
        }
        
        scrollView?.addObserver(self, forKeyPath: "contentOffset", options: .New, context: nil)
    }
    //移除kvo
    deinit {
        self.scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }

    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        let insertY = scrollView?.contentInset.top ?? 0
        
        let offSetY = scrollView?.contentOffset.y ?? 0
        
        let conditionValue = -(insertY + refreshHeight)
        
        //根据下拉的偏移值,设置刷新状态
        if scrollView!.dragging
    {
        //1.下拉超过了 insert + height 则 准备刷新
        if offSetY < conditionValue && refreshState == .Normal
        {
            refreshState = .Pulling
        }
        //2.加载完回去时候, 则 下拉刷新(默认)
        else if offSetY > conditionValue && refreshState == .Pulling
        {
            refreshState = .Normal
        }
    }
        //3.正在刷新状态
        else
        {
            if refreshState == .Pulling
            {
            refreshState = .Refreshing
            }
        }
//        print(insertY)
//        print(refreshState)
    }
    //从Home界面加载完毕后,把状态重置为normal
    func endRefresh() {
        let delta = dispatch_time(DISPATCH_TIME_NOW, Int64(1) * Int64(NSEC_PER_SEC))
        dispatch_after(delta, dispatch_get_main_queue()) { () -> Void in
            self.refreshState = .Normal
        }
    }
    
    
    private var scrollView : UIScrollView?
    
    private lazy var textLabel = UILabel(title: "下拉刷新", color: UIColor.blackColor(), fontSize: 14)
    
    private lazy var iconView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    
    private lazy var indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
}
